package com.ptbuy.upload;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ptbuy.base.BaseApplication;
import com.ptbuy.db.pojo.ClientPojo;
import com.ptbuy.db.pojo.ProductPojo;
import com.ptbuy.upload.ApiService;
import com.ptbuy.utils.Constants;
import com.ptbuy.utils.Utils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class Upload {

    private String addProdoctUrl = Constants.API + File.separator + "product" + File.separator + "addProduct/";
    private String removeProdoctUrl = Constants.API + File.separator + "product" + File.separator + "removeProduct/";
    private String modifyProdoctUrl = Constants.API + File.separator + "product" + File.separator + "modifyProduct/";
    private String addClientUrl = Constants.API + File.separator + "client" + File.separator + "addClient/";
    private String removeClientUrl = Constants.API + File.separator + "client" + File.separator + "removeClient/";
    private String modifyClientUrl = Constants.API + File.separator + "client" + File.separator + "modifyClient/";

    /**
     * 上传服务器 商品信息
     *
     * @param productPojo
     */
    public void addProdoctInfo(List<ProductPojo> productPojo) {

        new Thread(() -> {

            for (ProductPojo pd : productPojo) {
                pd.setDeveid(Utils.getDeviceId());
                String mult = pd.getMult();
                List<String> list = new ArrayList<>();
                if (mult != null && !"".equalsIgnoreCase(mult)) {
                    list = JSONObject.parseArray(mult, String.class);
                }

                // 创建Retrofit实例
                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl(addProdoctUrl)
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();

                // 创建服务实例
                ApiService apiService = retrofit.create(ApiService.class);

                List<MultipartBody.Part> parts = new ArrayList<>();

                for (String mu : list) {
                    File file = new File(mu);
                    RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                    MultipartBody.Part part = MultipartBody.Part.createFormData("multipartFile", file.getName(), fileBody);
                    parts.add(part);
                }

                // 创建RequestBody
                RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), JSON.toJSONString(pd));


                // 添加文件和描述到请求
                Call<ResponseBody> call = apiService.uploadFiles(
                        parts,
                        requestBody
                );
                // 执行请求
                call.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {


                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {

                    }
                });
            }

        }).start();


    }

    /**
     * 删除商品信息
     *
     * @param id
     */
    public void removeProdoctInfo(String id) {
        new Thread(() -> {
            removeAll(id, removeProdoctUrl);
        }).start();
    }

    /**
     * 修改商品信息
     *
     * @param productPojo
     */
    public void modifyProductInfo(ProductPojo productPojo) {
        new Thread(() -> {
            productPojo.setDeveid(Utils.getDeviceId());
            String mult = productPojo.getMult();
            List<String> list = new ArrayList<>();
            if (mult != null && !"".equalsIgnoreCase(mult)) {
                list = JSONObject.parseArray(mult, String.class);
            }

            // 创建Retrofit实例
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(modifyProdoctUrl)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();

            // 创建服务实例
            ApiService apiService = retrofit.create(ApiService.class);

            List<MultipartBody.Part> parts = new ArrayList<>();

            for (String mu : list) {
                File file = new File(mu);
                RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                MultipartBody.Part part = MultipartBody.Part.createFormData("multipartFile", file.getName(), fileBody);
                parts.add(part);
            }

            // 创建RequestBody
            RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), JSON.toJSONString(productPojo));


            // 添加文件和描述到请求
            Call<ResponseBody> call = apiService.uploadFiles(
                    parts,
                    requestBody
            );
            // 执行请求
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    System.out.println("sjkldf");

                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    System.out.println("sjkldf");
                }
            });
        }).start();
    }

    /**
     * 新增客户信息
     *
     * @param clientPojo
     */
    public void addClientInfo(ClientPojo clientPojo) {
        new Thread(() -> {
            clientPojo.setDeveid(Utils.getDeviceId());
            String mult = clientPojo.getSignatureFilePath();
            // 创建Retrofit实例
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(addClientUrl)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();

            // 创建服务实例
            ApiService apiService = retrofit.create(ApiService.class);
            List<MultipartBody.Part> parts = new ArrayList<>();
            if (mult != null && !"".equalsIgnoreCase(mult)) {
                File file = new File(mult);
                RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                MultipartBody.Part part = MultipartBody.Part.createFormData("multipartFile", file.getName(), fileBody);
                parts.add(part);
            }


            // 创建RequestBody
            RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), JSON.toJSONString(clientPojo));


            // 添加文件和描述到请求
            Call<ResponseBody> call = apiService.uploadFiles(
                    parts,
                    requestBody
            );
            // 执行请求
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {


                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {

                }
            });
        }).start();
    }

    /**
     * 删除客户信息
     *
     * @param id
     */
    public void removeClientInfo(String id) {
        new Thread(() -> {
            removeAll(id, removeClientUrl);
        }).start();
    }

    /**
     * 修改客户信息
     *
     * @param clientPojo
     */
    public void modifyClientInfo(ClientPojo clientPojo) {
        new Thread(() -> {
            try {
                OkHttpClient okHttpClient = new OkHttpClient.Builder()
                        .connectTimeout(15, TimeUnit.SECONDS)
                        .readTimeout(10, TimeUnit.HOURS)
                        .writeTimeout(10, TimeUnit.HOURS)
                        .build();
                FormBody body = new FormBody.Builder()
                        .add("clientPojo", JSON.toJSONString(clientPojo))
                        .build();
                Request.Builder builder = new Request.Builder()
                        .url(modifyClientUrl)
                        .post(body);
                Request request = builder.build();
                okHttpClient.newCall(request).execute();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }


    private void removeAll(String id, String url) {
        try {
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(15, TimeUnit.SECONDS)
                    .readTimeout(10, TimeUnit.HOURS)
                    .writeTimeout(10, TimeUnit.HOURS)
                    .build();

            Request.Builder builder = new Request.Builder()
                    .url(url + "?id=" + id)
                    .get();
            Request request = builder.build();
            okHttpClient.newCall(request).execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
